package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.UserAccountBindingMapper;
import org.linlinjava.litemall.db.domain.UserAccountBinding;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserAccountBindingService {

    @Resource
    private UserAccountBindingMapper bindingMapper;

    /**
     * 根据主键查询绑定关系
     */
    public UserAccountBinding findById(Long id) {
        return bindingMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据LiteMall用户ID查询绑定关系列表
     */
    public List<UserAccountBinding> queryByLitemallUserId(Integer litemallUserId) {
        if (litemallUserId == null) {
            return null;
        }
        return bindingMapper.selectByLitemallUserId(litemallUserId);
    }

    /**
     * 根据AMSP用户代码查询绑定关系列表
     */
    public List<UserAccountBinding> queryByAmspUserCode(String amspUserCode) {
        if (StringUtils.isEmpty(amspUserCode)) {
            return null;
        }
        return bindingMapper.selectByAmspUserCode(amspUserCode);
    }

    /**
     * 根据AMSP用户ID查询绑定关系列表
     */
    public List<UserAccountBinding> queryByAmspUserId(Integer amspUserId) {
        if (amspUserId == null) {
            return null;
        }
        return bindingMapper.selectByAmspUserId(amspUserId);
    }

    /**
     * 查询指定LiteMall用户的有效绑定关系(已绑定状态)
     */
    public UserAccountBinding findActiveBoundByLitemallUserId(Integer litemallUserId) {
        if (litemallUserId == null) {
            return null;
        }
        return bindingMapper.selectActiveBoundByLitemallUserId(litemallUserId);
    }

    /**
     * 查询指定AMSP用户的有效绑定关系(已绑定状态)
     */
    public UserAccountBinding findActiveBoundByAmspUserCode(String amspUserCode) {
        if (StringUtils.isEmpty(amspUserCode)) {
            return null;
        }
        return bindingMapper.selectActiveBoundByAmspUserCode(amspUserCode);
    }

    /**
     * 查询指定用户对的绑定关系
     */
    public UserAccountBinding findByLitemallUserIdAndAmspUserCode(Integer litemallUserId, String amspUserCode) {
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            return null;
        }
        return bindingMapper.selectByLitemallUserIdAndAmspUserCode(litemallUserId, amspUserCode);
    }

    /**
     * 创建绑定关系
     */
    public int add(UserAccountBinding binding) {
        if (binding == null) {
            return 0;
        }
        
        // 设置创建时间和更新时间
        Date now = new Date();
        if (binding.getCreatedAt() == null) {
            binding.setCreatedAt(now);
        }
        if (binding.getUpdatedAt() == null) {
            binding.setUpdatedAt(now);
        }
        
        // 如果是绑定状态，设置绑定时间
        if (UserAccountBinding.STATUS_BOUND.equals(binding.getBindingStatus()) && binding.getBindTime() == null) {
            binding.setBindTime(now);
        }
        
        return bindingMapper.insertSelective(binding);
    }

    /**
     * 更新绑定关系
     */
    public int updateById(UserAccountBinding binding) {
        if (binding == null || binding.getId() == null) {
            return 0;
        }
        
        // 设置更新时间
        binding.setUpdatedAt(new Date());
        
        return bindingMapper.updateByPrimaryKeySelective(binding);
    }

    /**
     * 绑定账户
     */
    public int bindAccount(Long id, Integer amspUserId) {
        if (id == null || amspUserId == null) {
            return 0;
        }
        return bindingMapper.bindAccount(id, amspUserId);
    }

    /**
     * 解绑账户
     */
    public int unbindAccount(Long id) {
        if (id == null) {
            return 0;
        }
        return bindingMapper.unbindAccount(id);
    }

    /**
     * 删除绑定关系
     */
    public int deleteById(Long id) {
        if (id == null) {
            return 0;
        }
        return bindingMapper.deleteByPrimaryKey(id);
    }

    /**
     * 条件查询绑定关系列表(支持分页)
     */
    public List<UserAccountBinding> querySelective(Integer litemallUserId, String amspUserCode, 
            Integer amspUserId, Integer bindingStatus, Integer page, Integer size) {
        
        if (page != null && size != null) {
            PageHelper.startPage(page, size);
        }
        
        return bindingMapper.selectSelective(litemallUserId, amspUserCode, amspUserId, bindingStatus);
    }

    /**
     * 统计绑定关系数量
     */
    public long countSelective(Integer litemallUserId, String amspUserCode, 
            Integer amspUserId, Integer bindingStatus) {
        return bindingMapper.countSelective(litemallUserId, amspUserCode, amspUserId, bindingStatus);
    }

    /**
     * 批量解绑指定LiteMall用户的所有账户
     */
    public int batchUnbindByLitemallUserId(Integer litemallUserId) {
        if (litemallUserId == null) {
            return 0;
        }
        return bindingMapper.batchUnbindByLitemallUserId(litemallUserId);
    }

    /**
     * 批量解绑指定AMSP用户代码的所有账户
     */
    public int batchUnbindByAmspUserCode(String amspUserCode) {
        if (StringUtils.isEmpty(amspUserCode)) {
            return 0;
        }
        return bindingMapper.batchUnbindByAmspUserCode(amspUserCode);
    }

    /**
     * 检查是否已存在绑定关系
     */
    public boolean isBindingExists(Integer litemallUserId, String amspUserCode) {
        UserAccountBinding binding = findByLitemallUserIdAndAmspUserCode(litemallUserId, amspUserCode);
        return binding != null;
    }

    /**
     * 检查是否已绑定
     */
    public boolean isBound(Integer litemallUserId, String amspUserCode) {
        UserAccountBinding binding = findByLitemallUserIdAndAmspUserCode(litemallUserId, amspUserCode);
        return binding != null && UserAccountBinding.STATUS_BOUND.equals(binding.getBindingStatus());
    }

    /**
     * 创建绑定关系（直接绑定）
     */
    public UserAccountBinding createBinding(Integer litemallUserId, String amspUserCode, Integer amspUserId) {
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            return null;
        }

        // 检查AMSP账号是否已被其他用户绑定
        UserAccountBinding existingAmspBinding = findActiveBoundByAmspUserCode(amspUserCode);
        if (existingAmspBinding != null && !existingAmspBinding.getLitemallUserId().equals(litemallUserId)) {
            throw new RuntimeException("AMSP账号 " + amspUserCode + " 已被其他用户绑定");
        }

        // 检查是否已存在绑定关系
        UserAccountBinding existingBinding = findByLitemallUserIdAndAmspUserCode(litemallUserId, amspUserCode);
        if (existingBinding != null) {
            // 如果已存在但未绑定，则更新为已绑定状态
            if (!UserAccountBinding.STATUS_BOUND.equals(existingBinding.getBindingStatus())) {
                existingBinding.setBindingStatus(UserAccountBinding.STATUS_BOUND);
                existingBinding.setAmspUserId(amspUserId);
                existingBinding.setBindTime(new Date());
                existingBinding.setUpdatedAt(new Date());
                updateById(existingBinding);
            }
            return existingBinding;
        }

        // 创建新的绑定关系（直接设为已绑定状态）
        UserAccountBinding binding = new UserAccountBinding();
        binding.setLitemallUserId(litemallUserId);
        binding.setAmspUserCode(amspUserCode);
        binding.setAmspUserId(amspUserId);
        binding.setBindingStatus(UserAccountBinding.STATUS_BOUND); // 直接设为已绑定状态
        
        Date now = new Date();
        binding.setCreatedAt(now);
        binding.setUpdatedAt(now);
        binding.setBindTime(now); // 设置绑定时间
        
        int result = bindingMapper.insertSelective(binding);
        return result > 0 ? binding : null;
    }



    /**
     * 获取用户的主要绑定账户
     */
    public UserAccountBinding getPrimaryBinding(Integer litemallUserId) {
        return findActiveBoundByLitemallUserId(litemallUserId);
    }

    /**
     * 检查AMSP账号是否已被绑定（不管是哪个用户）
     */
    public boolean isAmspAccountBound(String amspUserCode) {
        if (StringUtils.isEmpty(amspUserCode)) {
            return false;
        }
        UserAccountBinding binding = findActiveBoundByAmspUserCode(amspUserCode);
        return binding != null;
    }

    /**
     * 检查AMSP账号是否可以被指定用户绑定
     */
    public boolean canAmspAccountBindToUser(String amspUserCode, Integer litemallUserId) {
        if (StringUtils.isEmpty(amspUserCode) || litemallUserId == null) {
            return false;
        }
        
        UserAccountBinding existingBinding = findActiveBoundByAmspUserCode(amspUserCode);
        // 如果没有绑定关系，或者绑定的就是当前用户，则可以绑定
        return existingBinding == null || existingBinding.getLitemallUserId().equals(litemallUserId);
    }

    /**
     * 获取AMSP账号当前绑定的用户ID
     */
    public Integer getAmspAccountBoundUserId(String amspUserCode) {
        if (StringUtils.isEmpty(amspUserCode)) {
            return null;
        }
        UserAccountBinding binding = findActiveBoundByAmspUserCode(amspUserCode);
        return binding != null ? binding.getLitemallUserId() : null;
    }
} 